package pattern.singleton;

import java.io.*;
import java.util.concurrent.CountDownLatch;

/**
 * @author zhang peng yang ming
 * @create 2018-07-21 16:11
 */
public class SingletonMain {
    public static void main(String[] args) throws IOException, ClassNotFoundException, InterruptedException {
//        Singleton singleton = Singleton.getInstance();
//        Singleton singleton1 = Singleton.getInstance();
//        Singleton singleton2 = Singleton.getInstance();
//        Singleton singleton3 = Singleton.getInstance();
//        System.out.println(singleton);
//        System.out.println(singleton1);
//        System.out.println(singleton2);
//        System.out.println(singleton3);
//        System.out.println(singleton == singleton1);
//        System.out.println(singleton.equals(singleton1));
//        FileOutputStream fos = new FileOutputStream("singleto.txt");
//        ObjectOutputStream oos = new ObjectOutputStream(fos);
//        oos.writeObject(singleton);
//
//        FileInputStream fis = new FileInputStream("singleto.txt");
//        ObjectInput oi = new ObjectInputStream(fis);
//        Singleton singleton4 = (Singleton) oi.readObject();
//        System.out.println(singleton4);
//
//        System.out.println(singleton == singleton4);

        // 单例性能测试
        int threadNo = 100;
        final CountDownLatch cdl = new CountDownLatch(threadNo);

        long start = System.currentTimeMillis();
        for (int i = 0; i < 100; i++) {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    for (int i = 0; i < 10000; i++) {
//                        Object o1 = Singleton.getInstance();
                        Object o = SingletonLazySafe.getInstance();
                    }
                    cdl.countDown();
                }
            }).start();
        }

        cdl.await();
        long end = System.currentTimeMillis();

        System.out.println(end - start);
    }
}
